package com.moba.controller;

import com.alibaba.fastjson.JSONObject;
import com.moba.domain.*;
import com.moba.emums.*;
import com.moba.emums.orderInfo.OrderState;
import com.moba.emums.orderInfo.OrderType;
import com.moba.emums.orderInfo.PayType;
import com.moba.emums.roleUser.UserType;
import com.moba.service.*;
import com.moba.utils.FieldFilter;
import com.moba.utils.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author li, bai, qiang
 * @version 2019-03-04 14:10
 * @date 2019-03-04 14:10
 */
@RestController
@RequestMapping("/orderInfo")
@Api(tags = {"订单模块"})
public class OrderInfoController extends BaseUserController {

  @Resource OrderInfoService orderInfoService;
  @Resource UserInfoService userInfoService;
  @Resource UserWalletService userWalletService;
  @Resource SysSettingService sysSettingService;
  @Resource UserRelationParService userRelationParService;

  @ApiOperation(value = "获取列表")
  @GetMapping(value = "/getOrderList")
  public Object getOrderList(HttpServletRequest request, @ModelAttribute OrderInfo entity)
      throws Exception {

    JSONObject data = new JSONObject();

    data.put("count", orderInfoService.getEntityCount(entity));

    // 预约明天的订单
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    cal.add(Calendar.HOUR, 24); // 24小时制
    Date newDate = cal.getTime();

    entity.getMap().put("st_add_date", sdFormatYmd.format(newDate));
    entity.getMap().put("en_add_date", sdFormatYmd.format(newDate));
    data.put("count2", orderInfoService.getEntityCount(entity));

    // 每天下单最大上限
    SysSetting sys = getSysSetting(SysSettingType.orderMoneySumMax.getIndex());
    BigDecimal orderMoneySumMax = new BigDecimal(sys.getContent());
    logger.info("===每天下单最大上限===" + orderMoneySumMax);
    data.put("orderMoneySumMax", orderMoneySumMax);

    // 设置的当天下单虚假值
    sys = getSysSetting(SysSettingType.orderMoneySum.getIndex());
    BigDecimal orderMoneySum = new BigDecimal(sys.getContent());

    // 今天下单总额
    entity = new OrderInfo();
    entity.getMap().put("st_add_date", sdFormatYmd.format(new Date()));
    entity.getMap().put("en_add_date", sdFormatYmd.format(new Date()));
    data.put("sumOrderMoney", orderMoneySum.add(orderInfoService.getEntitySumOrderMoney(entity)));

    return ResultUtils.success(data);
  }

  @ApiOperation(value = "获取列表")
  @GetMapping(value = "/list")
  public Object list(
      HttpServletRequest request,
      @ModelAttribute OrderInfo entity,
      String stDate,
      String enDate,
      String user_name_like,
      Integer page)
      throws Exception {

    if (null == page) {
      page = 1;
    }

    JSONObject jsonObject = new JSONObject();
    Map<String, Object> paramMap = WebUtils.getParametersStartingWith(request, FieldFilter.PREFIX);
    FieldFilter.setQuery(paramMap, entity);

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z"); // 格式化的表达式
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    if (StringUtils.isNotBlank(stDate)) {
      stDate = stDate.replace("Z", " UTC"); // 是空格+UTC
      Date d = format.parse(stDate);
      stDate = simpleDateFormat.format(d);
      entity.getMap().put("st_add_date", stDate);
    }

    if (StringUtils.isNotBlank(enDate)) {
      enDate = enDate.replace("Z", " UTC"); // 是空格+UTC
      Date d = format.parse(enDate);
      enDate = simpleDateFormat.format(d);
      entity.getMap().put("en_add_date", enDate);
    }

    entity.getMap().put("user_name_like", user_name_like);

    jsonObject.put("dataCount", orderInfoService.getEntityCount(entity));
    entity.getRow().setCount(20);
    entity.getRow().setFirst((page - 1) * (entity.getRow().getCount()));
    List<OrderInfo> entityList = orderInfoService.getEntityPaginatedList(entity);
    jsonObject.put("entityList", entityList);

    jsonObject.put(
        "orderStateList", super.parseEnmuToJSONArray(OrderState.class, OrderState.values()));
    jsonObject.put(
        "orderTypeList", super.parseEnmuToJSONArray(OrderType.class, OrderType.values()));
    jsonObject.put("payTypeList", super.parseEnmuToJSONArray(PayType.class, PayType.values()));

    return ResultUtils.success(jsonObject);
  }

  @ApiOperation(value = "订单详情列表")
  @GetMapping(value = "/getOrderDetail")
  public Object getOrderDetail(Integer id) {

    OrderInfo entity = new OrderInfo();
    JSONObject jsonObject = new JSONObject();
    entity.setId(id);
    entity = orderInfoService.getEntity(entity);
    jsonObject.put("entity", entity);
    jsonObject.put(
        "orderStateList", super.parseEnmuToJSONArray(OrderState.class, OrderState.values()));
    jsonObject.put(
        "orderTypeList", super.parseEnmuToJSONArray(OrderType.class, OrderType.values()));
    jsonObject.put("payTypeList", super.parseEnmuToJSONArray(PayType.class, PayType.values()));
    if (null == entity) {
      return ResultUtils.error(CodeType.CODE_TYPE_102);
    }
    return ResultUtils.success(jsonObject);
  }

  @ApiOperation(value = "订单状态改变")
  @PostMapping(value = "/updateOrder")
  public Object updateOrder(@RequestBody OrderInfo entity) {

    if (null == entity.getId()) {
      return ResultUtils.error(CodeType.CODE_TYPE_102);
    }

    OrderInfo orderInfo = new OrderInfo();
    orderInfo.setId(entity.getId());
    orderInfo = orderInfoService.getEntity(orderInfo);
    if (null == orderInfo) {
      return ResultUtils.error(CodeType.CODE_TYPE_101);
    }

    entity.setUpdateDate(new Date());
    //        //当点取消状态时，前一个状态应为预定状态
    //        if (entity.getOrderState().intValue() == OrderState.ORDER_STATE_X10.getIndex()) {
    //            entity.getMap().put("orderStateFrontState", OrderState.ORDER_STATE_0.getIndex());
    //        }
    //        //当商家确认订单后进入发货状态，前一个状态应为等待发货状态
    //        if (entity.getOrderState().intValue() == OrderState.ORDER_STATE_20.getIndex()) {
    //            entity.setFahuoDate(new Date());
    //            entity.getMap().put("orderStateFrontState", OrderState.ORDER_STATE_10.getIndex());
    //        }
    //        //当买家确认商品后进入确认状态，前一个状态应为已支付状态
    //        if (entity.getOrderState().intValue() == OrderState.ORDER_STATE_40.getIndex()) {
    //            entity.setQrshDate(new Date());
    //            entity.getMap().put("orderStateFrontState", OrderState.ORDER_STATE_20.getIndex());
    //        }
    int count = orderInfoService.updateEntity(entity);
    if (count <= 0) {
      return ResultUtils.error(CodeType.CODE_TYPE_100);
    }
    return ResultUtils.success();
  }

  public SimpleDateFormat sdFormatymdhmsS = new SimpleDateFormat("yyyyMMddhhmmssSSS");

  @ApiOperation(value = "保存")
  @PostMapping(value = "/save")
  public Object save(@RequestBody @Valid OrderInfo entity, BindingResult result) {

    if (null == entity.getId()) {
      int maxOderCount = 5;

      // 查询系统设置轮回单数 默认3单
      SysSetting sys = getSysSetting(SysSettingType.dayCountRetrun.getName());
      if (null != sys) {
        maxOderCount = Integer.valueOf(sys.getContent());
      }
      entity.getMap().put("maxOderCount", maxOderCount);

      UserInfo user = getUserInfo(entity.getAddUserId());
      if (user == null) {
        return ResultUtils.error(CodeType.CODE_TYPE_104, "用户不存在！");
      }

      entity.getMap().put("userInfo", user);

      // 查询汇率
      BigDecimal rate = new BigDecimal(2);
      try {
        //        rate = WalletHelp.getExchangeRate("GHMI");
        //        logger.info("=====rate:" + rate);
      } catch (Exception e) {

      }

      // *********用于测试,后期开发去掉*********
      rate = new BigDecimal(0.2329);
      if (rate.compareTo(new BigDecimal(0)) == 0) {
        return ResultUtils.error(CodeType.CODE_TYPE_104, "GHMI汇率查询失败！");
      }

      entity.setOrderMoney(entity.getOrderMoney().multiply(rate));

      // 判断用户矿源是否足够
      sys = new SysSetting();
      sys.setMemo(SysSettingType.orderProfitRatio.getIndex());
      BigDecimal 订单出金比例 =
          new BigDecimal(sysSettingService.getEntity(sys).getContent()).divide(new BigDecimal(100));

      BigDecimal 收益金额 =
          entity.getOrderMoney().multiply(new BigDecimal(maxOderCount)).multiply(订单出金比例);
      if (user.getOrderMoneySum().compareTo(收益金额) < 0) {
        return ResultUtils.error(CodeType.CODE_TYPE_104, "矿源不足请充值！");
      }
      entity.getMap().put("subOrderMoneySum", 收益金额);

      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

      // 每天下单最大上限
      sys = getSysSetting(SysSettingType.orderMoneySumMax.getIndex());
      BigDecimal orderMoneySumMax = new BigDecimal(sys.getContent());
      logger.info("===每天下单最大上限===" + orderMoneySumMax);

      // 设置的当天下单虚假值
      sys = getSysSetting(SysSettingType.orderMoneySum.getIndex());
      BigDecimal orderMoneySum = new BigDecimal(sys.getContent());

      // 今日矿机限额是否已满
      OrderInfo orderInfo = new OrderInfo();
      orderInfo.getMap().put("st_add_date", sdf.format(new Date()));
      orderInfo.getMap().put("en_add_date", sdf.format(new Date()));
      BigDecimal moneyBiSum = orderInfoService.getEntitySumOrderMoney(orderInfo);
      logger.info("===已下单金额===" + moneyBiSum);
      logger.info("===已下单金额+虚假金额===" + moneyBiSum.add(orderMoneySum));

      if (moneyBiSum.add(orderMoneySum).compareTo(orderMoneySumMax) > 0) {
        // 今日已满 预约明天的单
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.HOUR, 24); // 24小时制
        Date newDate = cal.getTime();
        entity.setRunDate(newDate);
      } else {
        entity.setRunDate(new Date());
      }

      // 下单时间间隔
      // 再次购买间隔时间（小时）
      Integer addOrderTimeInterval =
          new Integer(super.getSysSetting("addOrderTimeInterval").getContent());
      logger.info("===再次购买间隔时间（小时）===" + addOrderTimeInterval);

      // 获取上一次下单时间
      sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

      int subDay = 0;
      // 获取用户已下的订单
      orderInfo = new OrderInfo();
      orderInfo.setAddUserId(entity.getAddUserId());
      logger.info("====获取用户已下的订单====");
      List<OrderInfo> alist = orderInfoService.getEntityList(orderInfo);
      if (null != alist && alist.size() > 0) {
        logger.info("===用户下过订单===");
        orderInfo = alist.get(0);

        // 是否能够再次下单
        Calendar cal = Calendar.getInstance();
        cal.setTime(orderInfo.getAddDate());
        cal.add(Calendar.HOUR, addOrderTimeInterval); // 24小时制
        Date newAddOrderTime = cal.getTime();
        logger.info("再次下单时间:" + sdf.format(newAddOrderTime));
        logger.info("当前时间:" + sdf.format(new Date()));
        if (newAddOrderTime.getTime() > new Date().getTime()) {
          // TODO
          //          return ResultUtils.error(CodeType.CODE_TYPE_104, "未到再次排单时间！");
        }
        logger.info("===可以继续下单===");
        //        subDay = differentDaysByMillisecond(orderInfo.getAddDate(), new Date());
      } else {

        logger.info("===用户未下过单===");
      }

      entity.setTradeIndex(this.creatTradeIndex());

      OrderInfo tempOrder = new OrderInfo();
      tempOrder.setAddUserId(entity.getAddUserId());
      tempOrder.setOrderState(OrderState.ORDER_STATE_10.getIndex());
      tempOrder.getMap().put("order_by_id_asc", "true");
      // 获取当前用户有几轮订单
      List<OrderInfo> tempOrderList = orderInfoService.getDistinctTempList(tempOrder);
      if (null == tempOrderList || tempOrderList.size() == 0) {
        entity.setTemp(entity.getTradeIndex());
      } else {
        tempOrder = tempOrderList.get(tempOrderList.size() - 1);

        String temp = tempOrder.getTemp();
        OrderInfo newTempOrder = new OrderInfo();
        newTempOrder.setTemp(temp);
        newTempOrder.getMap().put("order_by_id_asc", "true");
        List<OrderInfo> newTempOrderList = orderInfoService.getEntityList(newTempOrder);

        if (newTempOrderList.size() >= maxOderCount) {
          logger.info("====新的轮回");
          entity.setTemp(entity.getTradeIndex());
        } else {
          newTempOrder = newTempOrderList.get(0);
          logger.info("newTempOrder.getTradeIndex():" + newTempOrder.getTradeIndex());
          logger.info("newTempOrder.getTemp():" + newTempOrder.getTemp());

          subDay = differentDaysByMillisecond(newTempOrder.getAddDate(), new Date());
          logger.info("=====相差天数subDay:" + subDay);
          if (subDay >= maxOderCount) {
            logger.info("====新的轮回");
            entity.setTemp(entity.getTradeIndex());
          } else {
            logger.info("====同一个轮回");
            entity.setTemp(newTempOrder.getTemp());
          }
        }
      }

      // 判断排单金额是否在范围之内
      BaseData bd = super.getBaseDataById(BaseDataId.BaseDataId_90.getIndex());
      logger.info("===开始检测订单金额是否在范围之内===");
      logger.info("===当前订单金额===" + entity.getOrderMoney());
      logger.info("===范围===" + bd.getTypeValue() + "至" + bd.getValue());
      if (entity.getOrderMoney().compareTo(new BigDecimal(bd.getTypeValue())) < 0
          || entity.getOrderMoney().compareTo(new BigDecimal(bd.getValue())) > 0) {
        return ResultUtils.error(CodeType.CODE_TYPE_104, "金额范围：200U-1000U");
      }
      logger.info("===订单金额在范围之内===继续执行===");
      orderInfo = new OrderInfo();

      orderInfo.setAddUserId(entity.getAddUserId());
      orderInfo.setOrderState(OrderState.ORDER_STATE_10.getIndex());

      // 调用钱包接口查询GHMI是否足够
      UserWallet userWallet = new UserWallet();
      userWallet.setUserId(entity.getAddUserId());
      userWallet = userWalletService.getEntity(userWallet);
      if (userWallet == null) {
        return ResultUtils.error(CodeType.CODE_TYPE_104, "用户钱包不存在！");
      }
      if (StringUtils.isBlank(userWallet.getEcr20Address())) {
        return ResultUtils.error(CodeType.CODE_TYPE_104, "用户GHMI钱包地址错误！");
      }
      // ghmi总金额
      BigDecimal ghmi_total = new BigDecimal(10000);
      try {
        //        ghmi_total = new
        // BigDecimal(WalletHelp.getERC20Balance(userWallet.getEcr20Address()));
      } catch (Exception e) {

      }

      // *********用于测试,后期开发去掉*********
      ghmi_total = new BigDecimal(20000);

      // 查询冻结中也就是排单中的GHMI金额
      // 已使用的ghmi金额
      BigDecimal ghmi_used = orderInfoService.getEntitySumMoneyBi(orderInfo);

      // 实际剩余ghmi金额
      BigDecimal ghmi_has = ghmi_total.subtract(ghmi_used);
      System.out.println("=======ghmi_need=========" + ghmi_has);
      entity.getMap().put("ghmi_has", ghmi_has);

      logger.info("===当前【拥有】ghmi金额：" + ghmi_has);

      // 需要的ghmi金额
      BigDecimal ghmi_need = entity.getOrderMoney().divide(rate);
      logger.info("===当前【需要】ghmi金额：" + ghmi_need);
      if (ghmi_has.compareTo(ghmi_need) < 0) {
        // 一个usdt浮动空间
        ghmi_need = (entity.getOrderMoney().subtract(new BigDecimal(1))).multiply(rate);

        if (ghmi_has.compareTo(ghmi_need) < 0) {

          return ResultUtils.error(CodeType.CODE_TYPE_104, "GHMI余额不足！");
        }

        entity.setMoneyBi(ghmi_has);
      } else {
        entity.setMoneyBi(ghmi_need);
      }

      entity.setMatflowPrice(收益金额);
      Calendar cal = Calendar.getInstance();
      cal.setTime(new Date());
      cal.add(Calendar.HOUR, 24 * 5); // 24小时制
      Date newDate = cal.getTime();

      entity.setEndDate(newDate);
      entity.setGhmiRate(rate);
      entity.setAddUserName(user.getMobile());
      entity.setAddDate(new Date());

      entity.setOrderState(OrderState.ORDER_STATE_10.getIndex());
      entity.getMap().put("add_leiji_money_user", entity.getOrderMoney());

      logger.info("===创建订单===");
      orderInfoService.createEntity(entity);
    } else {
      entity.setUpdateDate(new Date());
      entity.getMap().put("update_newsInfo", true);
      orderInfoService.updateEntity(entity);
    }
    return ResultUtils.success();
  }

  /**
   * @author Wu, Yang
   * @date 2011-09-06 生成订单交易流水号,长度：22位，（前17位：4年2月2日2时2分2秒3毫秒） + （后三位：3SEQ）
   * @desc 后三位根据SEQ_ORDER_INFO_TRADE_INDEX生成，最大999循环生成
   */
  public String creatTradeIndex() {
    // BigDecimal trade_index = getFacade().getOrderInfoService().genOrderInfoTradeIndex(new
    // OrderInfo());
    String trade_no = sdFormatymdhmsS.format(new Date());

    return trade_no;
  }

  @ApiOperation(value = "查询单条记录")
  @GetMapping(value = "/{id}")
  public Object edit(@PathVariable(name = "id") Integer id) {

    OrderInfo entity = new OrderInfo();
    entity.setId(id);
    entity = orderInfoService.getEntity(entity);
    if (null == entity) {
      return ResultUtils.error(CodeType.CODE_TYPE_102);
    }
    return ResultUtils.success(entity);
  }

  @ApiOperation(value = "app首页")
  @GetMapping(value = "/appIndex")
  public Object appIndex(HttpServletRequest request) {

    JSONObject jsonObject = new JSONObject();

    OrderInfo entity = new OrderInfo();
    entity.setOrderState(OrderState.ORDER_STATE_10.getIndex());
    entity.getRow().setCount(20);
    entity.getRow().setFirst(0);
    List<OrderInfo> entityList = orderInfoService.getEntityPaginatedList(entity);
    jsonObject.put("entityList", entityList);

    return ResultUtils.success(jsonObject);
  }

  @ApiOperation(value = "钱包列表")
  @GetMapping(value = "/userOrder")
  public Object userOrder(HttpServletRequest request, @ModelAttribute OrderInfo entity) {
    JSONObject data = new JSONObject();
    BigDecimal orderMoney = orderInfoService.getEntitySumMoneyBi(entity);
    data.put("orderMoney", orderMoney);

    UserWallet userWallet = new UserWallet();
    userWallet.setUserId(entity.getAddUserId());
    userWallet = userWalletService.getEntity(userWallet);

    if (userWallet == null) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "用户钱包不存在！");
    }
    if (StringUtils.isBlank(userWallet.getEcr20Address())) {
      return ResultUtils.error(CodeType.CODE_TYPE_104, "用户GHMI钱包地址错误！");
    }
    BigDecimal ghmi_total = new BigDecimal(10000);
    try {
      //      ghmi_total = new BigDecimal(WalletHelp.getERC20Balance(userWallet.getEcr20Address()));
    } catch (Exception e) {
      ghmi_total = new BigDecimal(10000);
    }

    // *********用于测试,后期开发去掉*********
    ghmi_total = new BigDecimal(10000);

    data.put("ghmi", ghmi_total);

    return ResultUtils.success(data);
  }

  @ApiOperation(value = "冻结订单")
  @GetMapping(value = "/ghmiOrder")
  public Object ghmiOrder(Integer id) {
    JSONObject data = new JSONObject();
    OrderInfo orderInfo = new OrderInfo();
    orderInfo.setAddUserId(id);
    orderInfo.setOrderState(OrderState.ORDER_STATE_10.getIndex());
    BigDecimal orderMoney = orderInfoService.getEntitySumMoneyBi(orderInfo);
    data.put("orderMoney", orderMoney);
    System.out.println("==========================" + orderMoney);
    return ResultUtils.success(data);
  }

  @ApiOperation(value = "执行定时任务")
  @GetMapping(value = "/orderPriceJob")
  public Object orderPriceJob() {
    logger.info("===orderPriceJob===start");
    int 订单轮回天数 = 5;

    // 查询系统设置轮回天数
    SysSetting sys = new SysSetting();
    sys.setMemo(SysSettingType.dayCountRetrun.getIndex());
    sys = sysSettingService.getEntity(sys);
    if (null != sys) {
      订单轮回天数 = Integer.valueOf(sys.getContent());
    }

    // 订单出金比例
    sys = new SysSetting();
    sys.setMemo(SysSettingType.orderProfitRatio.getIndex());
    BigDecimal 订单出金比例 =
        new BigDecimal(sysSettingService.getEntity(sys).getContent()).divide(new BigDecimal(100));

    BigDecimal ranshao = new BigDecimal(0);
    sys = new SysSetting();
    sys.setMemo(SysSettingType.shaoShangSubValue.getIndex());
    sys = sysSettingService.getEntity(sys);
    if (null != sys) {
      ranshao = new BigDecimal(sys.getContent());
    }

    // 查出所有用户
    UserInfo userInfo = new UserInfo();
    userInfo.setIsDel(0);
    userInfo.setUserType(UserType.USER_TYPE_2.getIndex());
    //    userInfo.getMap().put("order_count_gt_0", "true");
    List<UserInfo> userInfoList = userInfoService.getEntityList(userInfo);
    if (null == userInfoList || userInfoList.size() == 0) {
      return ResultUtils.success();
    }

    userInfoList:
    for (UserInfo itemUser : userInfoList) {
      // 用户所有订单
      OrderInfo orderInfo = new OrderInfo();
      orderInfo.setAddUserId(itemUser.getId());
      orderInfo.setOrderState(OrderState.ORDER_STATE_10.getIndex());
      orderInfo.getMap().put("order_by_id_asc", "true");
      List<OrderInfo> orderInfoList = orderInfoService.getEntityList(orderInfo);
      if (null == orderInfoList || orderInfoList.size() == 0) {
        continue;
      }

      logger.info("===订单数量:" + orderInfoList.size());

      if (orderInfoList.size() == 1) {
        logger.info("===只有最后一个订单 锁定=====");
        logger.info("===只有最后一个订单 锁定=====");
        logger.info("===只有最后一个订单 锁定=====");
        continue;
      }

      // 获取当前用户有几轮订单
      List<OrderInfo> tempList = orderInfoService.getDistinctTempList(orderInfo);

      // 获取有几轮
      int 轮数 = tempList.size();
      logger.info("轮数:" + 轮数);

      // 判断当前用户订单是否锁定
      // 最后一个订单金额是不是最大的
      // 获取当前收益的订单
      OrderInfo thisOrder = orderInfoList.get(0);
      logger.info("===当前受益订单金额:" + thisOrder.getOrderMoney());

      // 判断当前订单是否满了一个轮回
      OrderInfo tempOrder = new OrderInfo();
      tempOrder.setTemp(thisOrder.getTemp());
      tempOrder.getMap().put("order_by_id_asc", "true");
      List<OrderInfo> tempOrderList = orderInfoService.getEntityList(tempOrder);
      // 订单不满足一个轮回数直接跳过
      if (null == tempOrderList || tempOrderList.size() == 0) {
        logger.info("轮回编号:" + thisOrder.getTemp() + "不满一个轮回");
        continue;
      }

      tempOrder = tempOrderList.get(0);
      // 判断轮回中第一个订单的添加时间与现在的时间对比 是否大于一个周期
      int subDay = super.differentDaysByMillisecond(tempOrder.getAddDate(), new Date());
      logger.info("===周期中第一个订单的添加时间与现在的时间差值:" + subDay);
      if (subDay < 订单轮回天数) {
        logger.info("====不满一个周期===跳出");
        continue userInfoList;
      }

      boolean 是否出单 = false;

      logger.info("=====当前订单金额：" + thisOrder.getOrderMoney() + "====id:" + thisOrder.getId());
      // 判断当前轮回中是否锁定
      tempOrderList:
      for (OrderInfo itemOrder : tempOrderList) {
        if (itemOrder.getId().intValue() == thisOrder.getId().intValue()) {
          continue tempOrderList;
        }
        if (itemOrder.getOrderState().intValue() == OrderState.ORDER_STATE_50.getIndex()) {
          continue tempOrderList;
        }
        logger.info("=====对比的订单金额" + itemOrder.getOrderMoney() + "====id:" + itemOrder.getId());

        // 一轮中后面的订单 有比当前订单金额 >=的 就出单
        if (itemOrder.getOrderMoney().compareTo(thisOrder.getOrderMoney()) >= 0) {
          是否出单 = true;
        }
      }

      if (!是否出单) {
        // 不出单直接跳到下个用户
        // 当前轮回不出单，再判断是否有别的轮订单

        if (轮数 < 2) {
          logger.info("===不出单===");
          logger.info("===不出单===");
          logger.info("===不出单===");

          OrderInfo updateOrder = new OrderInfo();
          updateOrder.setIsOpt(1);
          updateOrder.getMap().put("order_state", OrderState.ORDER_STATE_10.getIndex());
          updateOrder.getMap().put("temp", thisOrder.getTemp());
          orderInfoService.updateEntity(updateOrder);

          continue userInfoList;
        }
        logger.info("===开始计算下一轮订单====");
        // 上一轮中订单被锁定，在后面的订单中判断是否能出单

        // 循环轮数 这里只有temp值
        tempList:
        for (OrderInfo a : tempList) {
          String tempIndex = a.getTemp();
          if (tempIndex.equals(thisOrder.getTemp())) {
            continue tempList;
          }
          OrderInfo thisTempOrder = new OrderInfo();
          thisTempOrder.setTemp(tempIndex);
          List<OrderInfo> thisTempOrderList = orderInfoService.getEntityList(thisTempOrder);
          thisTempOrderList:
          for (OrderInfo b : thisTempOrderList) {
            if (b.getOrderMoney().compareTo(thisOrder.getOrderMoney()) >= 0) {
              logger.info("====解锁===可以出单===");
              是否出单 = true;
              break tempList;
            }
          }
        }
      }
      if (!是否出单) {
        // 不出单直接跳到下个用户
        logger.info("===不出单===");
        logger.info("===不出单===");
        logger.info("===不出单===");

        OrderInfo updateOrder = new OrderInfo();
        updateOrder.setIsOpt(1);
        updateOrder.getMap().put("addUserId", thisOrder.getAddUserId());
        updateOrder.getMap().put("order_state", OrderState.ORDER_STATE_10.getIndex());
        //        updateOrder.getMap().put("id_xiaoyu", thisOrder.getTemp());
        orderInfoService.updateEntity(updateOrder);

        continue;
      }

      OrderInfo updateOrder = new OrderInfo();
      updateOrder.setIsOpt(1);
      updateOrder.getMap().put("temp", thisOrder.getTemp());
      updateOrder.getMap().put("order_state", OrderState.ORDER_STATE_10.getIndex());
      updateOrder.getMap().put("not_in_id", thisOrder.getId());
      logger.info("====该轮订单都锁定=====");
      orderInfoService.updateEntity(updateOrder);

      BigDecimal 收益金额 = thisOrder.getOrderMoney().multiply(new BigDecimal(订单轮回天数)).multiply(订单出金比例);
      logger.info("===收益金额:" + 收益金额);

      thisOrder.setIsOpt(0);
      thisOrder.setOrderState(OrderState.ORDER_STATE_50.getIndex());
      thisOrder.setFahuoDate(new Date()); // 发放奖励时间
      thisOrder.setProfitMoney(收益金额);
      thisOrder.getMap().put("send_gusd", 收益金额.add(thisOrder.getOrderMoney()));
      thisOrder.getMap().put("ranshao", ranshao);
      orderInfoService.updateEntity(thisOrder);
    }
    return ResultUtils.success();
  }

  @ApiOperation(value = "执行定时任务-订单奖励")
  @GetMapping(value = "/userLeveUp")
  public Object userLeveUp() {
    logger.info("===orderReward===start");
    int 订单轮回天数 = 5;

    // 查询系统设置轮回天数
    SysSetting sys = new SysSetting();
    sys.setMemo(SysSettingType.dayCountRetrun.getIndex());
    sys = sysSettingService.getEntity(sys);
    if (null != sys) {
      订单轮回天数 = Integer.valueOf(sys.getContent());
    }
    sys = super.getSysSetting(SysSettingType.shaoShangSubValue.getIndex());
    BigDecimal shaoshang = new BigDecimal(sys.getContent());

    List<BaseData> baseDataList = super.getBaseDataList(BaseDataType.BaseDataType_200.getIndex());

    BaseData baseLevel = super.getBaseDataById(UserLevel.USER_LEVEL_200.getIndex());
    BaseData ontLevel = super.getBaseDataById(UserLevel.USER_LEVEL_201.getIndex());
    BaseData twoLevel = super.getBaseDataById(UserLevel.USER_LEVEL_202.getIndex());
    BaseData treeLevel = super.getBaseDataById(UserLevel.USER_LEVEL_203.getIndex());
    BaseData fourLevel = super.getBaseDataById(UserLevel.USER_LEVEL_204.getIndex());

    UserInfo a = new UserInfo();
    a.setIsDel(0);
    List<UserInfo> alist = userInfoService.getEntityList(a);
    for (UserInfo item : alist) {
      System.out.println("");
      System.out.println("=====user_name:" + item.getUserName());
      UserRelationPar b = new UserRelationPar();
      b.setUserParId(item.getId());
      BigDecimal sumMoneyLeiji = userRelationParService.getUserSonSumMoneyLeiji(b);

      logger.info("======" + item.getUserName() + "===该用户团队收益总和:" + sumMoneyLeiji);

      boolean isSend = false;
      int updateLevel = 200;
      int count = 0;

      UserInfo ymidUser = new UserInfo();
      ymidUser.setYmid(item.getMobile());
      ymidUser.setIsDel(0);
      List<UserInfo> ymidUserList = userInfoService.getEntityList(ymidUser);

      BaseData userData = super.getBaseDataById(item.getUserLevel());
      logger.info("=====" + userData.getValue() + "===" + userData.getId());

      if (item.getUserLevel().intValue() == 200) {
        if (item.getLeijiMoneyUser().compareTo(ontLevel.getValue2()) >= 0) {
          // 发放奖励
          isSend = true;
          updateLevel = ontLevel.getId();
          logger.info(item.getUserName() + "===升级为" + ontLevel.getTypeName());
        }
      }
      logger.info("===updateLevel:" + updateLevel);

      if (item.getUserLevel() < 201 || updateLevel == 201) {
        logger.info("升级到G2=====判断是否有3个G1======");
        // 三个G1
        int countTwo = 0;
        // 下级是否有3个G1
        // 3个不同区域的G1，先把用户的下1级用户列出来（各条支路）
        // 再查各支路中是否有满足G1用户

        ymidUserList:
        for (UserInfo user : ymidUserList) {
          logger.info("=====用户:" + user.getUserName());
          // 循环各条线路
          // 判断线路中是否有用户达到G1
          // 1.自己是否满足
          if (user.getLeijiMoneyUser().compareTo(twoLevel.getValue2()) >= 0) {
            logger.info(user.getUserName() + "====自己满足升级条件====");
            countTwo++;
            continue ymidUserList;
          }
          // 2.自己不满足 在看自己的团队
          UserRelationPar c = new UserRelationPar();
          c.setUserParId(user.getId());
          List<UserRelationPar> sonList = userRelationParService.getEntityList(c);
          sonList:
          for (UserRelationPar sonItem : sonList) {
            if (new BigDecimal(sonItem.getMap().get("leijiMoneyUser").toString())
                    .compareTo(twoLevel.getValue2())
                >= 0) {
              logger.info("====满足升级条件====");
              countTwo++;
              break sonList;
            }
          }
        }
        logger.info("====满足个数" + countTwo);
        if (countTwo >= 3) {
          logger.info("===升级为" + twoLevel.getTypeName());
          isSend = true;
          updateLevel = twoLevel.getId();
        }
      }
      if (item.getUserLevel() < 202 || updateLevel == 202) {
        // 升级G3
        logger.info("升级到G3=======判断是否有3个G2======");
        // 三个G1
        int countTree = 0;
        // 下级是否有3个G2
        // 3个不同区域的G2，先把用户的下1级用户列出来（各条支路）
        // 再查各支路中是否有满足G2用户

        ymidUserList:
        for (UserInfo user : ymidUserList) {
          logger.info("=====用户:" + user.getUserName());
          // 循环各条线路
          // 判断线路中是否有用户达到G1
          // 1.自己是否满足

          if (user.getUserLevel() >= twoLevel.getId()) {
            countTree++;
            continue ymidUserList;
          }

          // 2.自己不满足 在看自己的团队
          UserRelationPar c = new UserRelationPar();
          c.setUserParId(user.getId());
          List<UserRelationPar> sonList = userRelationParService.getEntityList(c);
          sonList:
          for (UserRelationPar sonItem : sonList) {
            Integer sonLevel = new Integer(sonItem.getMap().get("userLevel").toString());
            if (sonLevel >= twoLevel.getId()) {
              countTree++;
              break sonList;
            }
          }
        }
        logger.info("====满足个数" + count);
        if (countTree >= 3) {
          logger.info("===升级为" + treeLevel.getTypeName());
          isSend = true;
          updateLevel = treeLevel.getId();
        }
      }

      if (item.getUserLevel() < 203 || updateLevel == 203) {
        // 升级G4
        logger.info("==升级到G4=====判断是否有3个G3======");
        // 三个G3
        int thisCount = 0;
        // 下级是否有3个G2
        // 3个不同区域的G2，先把用户的下1级用户列出来（各条支路）
        // 再查各支路中是否有满足G2用户

        ymidUserList:
        for (UserInfo user : ymidUserList) {
          logger.info("=====用户:" + user.getUserName());

          if (user.getUserLevel() >= treeLevel.getId()) {
            thisCount++;
            continue ymidUserList;
          }

          // 2.自己不满足 在看自己的团队
          UserRelationPar c = new UserRelationPar();
          c.setUserParId(user.getId());
          List<UserRelationPar> sonList = userRelationParService.getEntityList(c);
          sonList:
          for (UserRelationPar sonItem : sonList) {
            Integer sonLevel = new Integer(sonItem.getMap().get("userLevel").toString());
            if (sonLevel >= treeLevel.getId()) {
              thisCount++;
              break sonList;
            }
          }
        }
        logger.info("====满足个数" + count);
        if (thisCount >= 3) {
          logger.info("===升级为" + fourLevel.getTypeName());
          isSend = true;
          updateLevel = fourLevel.getId();
        }
      }

      if (isSend) {
        UserInfo updateUser = new UserInfo();
        updateUser.setId(item.getId());
        updateUser.setUserLevel(updateLevel);
        userInfoService.updateEntity(updateUser);
      }
    }

    UserInfo updateUser = new UserInfo();
    updateUser.getMap().put("sned_team_price", "true");
    userInfoService.updateEntity(updateUser);
    return ResultUtils.success();
  }
}
